package com.woniuxy.redisconf;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author: 马宇航
 * @Do: 配置类，配置redis要用的东西，redisTemplate，序列化方案
 * @DateTime: 22/05/27/0027 上午 10:42
 * @Component: 成都蜗牛学苑
 **/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    //RedisTemplate 配置
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        //创建redisTemplate对象
        RedisTemplate redisTemplate = new RedisTemplate();
        //设置连接工厂
        redisTemplate.setConnectionFactory(factory);
        //由于Redis需要将传入的对象进行序列化与反序列化，所以需要做如下配置
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setValueSerializer(RedisSerializer.json());
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        return redisTemplate;
    }

    //配置SpringCache整合redis 配置RedisCacheConfiguration bean对象
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        //使用默认缓存配置
        //配置序列化方案
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig().serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return configuration;
    }
}
